package homework.test1


import scala.io.StdIn

object DecomposePrime {
  def isPrime(p: Int): Boolean = {
    if (p <= 1) false
    else if (p == 2) true
    else if (p % 2 == 0) false
    else {
      val num = Math.sqrt(p).toInt
      for (i <- 3 to num by 2) {
        if (p % i == 0) return false
      }
      true
    }
  }


  def main(args: Array[String]): Unit = {
    println("请输入一个数字")
    var num = StdIn.readInt()


    if (num <= 1) {
      println(s"$num 不是正整数，无法分解质因数。")
      return
    }


    if (isPrime(num)) {
      println(s"$num = $num")
      return
    }

    // 分解质因数
    val factors = scala.collection.mutable.ListBuffer[Int]()
    var tempNum = num

    // 检查2是否为因子
    while (tempNum % 2 == 0) {
      factors += 2
      tempNum /= 2
    }

    // 检查奇数是否为因子
    var divisor = 3
    while (divisor <= Math.sqrt(tempNum)) {
      while (tempNum % divisor == 0) {
        factors += divisor
        tempNum /= divisor
      }
      divisor += 2
    }

    // 如果剩下的数字大于1，说明它是一个质数
    if (tempNum > 1) {
      factors += tempNum
    }

    // 打印结果
    val factorString = factors.mkString(" * ")
    println(s"$num = $factorString")
  }
}
